from django.shortcuts import render
from django.views import View
from common.goods import get_categories,get_breadcrumb
from apps.contents.models import ContentCategory

#模板渲染 静态话生成HTML
class IndexView(View):
    def get(self,request):  #定义首页
        # 分类
        categories=get_categories()
        #广告
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        context={
            'categories': categories,
            'contents': contents,

        }
        #三个参数：请求 模板名字 渲染数据
        return render(request,'index.html',context=context)

from django.http import JsonResponse
from apps.goods.models import GoodsCategory,SKU
from django.core.paginator import Paginator
from haystack.views import SearchView
from common.goods import get_goods_specs
from datetime import date
from apps.goods.models import GoodsVisitCount


class ListView(View):
    def get(self,request,category_id):

    #面包屑
    # 1.获取分类id 2.根据id查询分类数据 3.获取排序和分页数据
    #4.查询类别数据 5.分页操作 6对象列表转换字典 7返回
        try:
            category=GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此分类'})

        breadcrumb=get_breadcrumb(category)

        ordering=request.GET.get('ordering')
        page=request.GET.get('page',1)

        page_size=request.GET.get('page_size',5)#每页的记录条数

        skus=SKU.objects.filter(category,is_launched=True).order_by(ordering)

        paginator=Paginator(skus,per_page=page_size)

        page_sku=paginator.page(page)

        total_page=paginator.num_pages

        sku_list=[]
        for sku in page_sku:
            sku_list.append(({'id':sku.id,
                              'name':sku.name,
                              'price':sku.price,
                              'default_image_url':sku.default_image.url,}))

        return JsonResponse({
            'code':0,
            'count':total_page,
            'breadcrumb':breadcrumb,
            'list':sku_list
        })


class HotView(View):

    def get(self,request,category_id):

#获取分类id，根据id查询，排序获取2条记录
#查询的对象列表转换字典列表
                                               #获取从大到小降序前两个数据
        skus=SKU.objects.filter(category_id=category_id).order_by('-sales')[0:2]


        hot_skus=[]
        for sku in skus:
            hot_skus.append(({'id':sku.id,
                                      'name':sku.name,
                                      'price':sku.price,
                                      'default_image_url':sku.default_image.url,}))

        return JsonResponse({
                    'code':0,'hot_skus':hot_skus})


#搜索商品
class MeiduoSearchView(SearchView):
    '''重写SearchView类'''

    def create_response(self):
        page = self.request.GET.get('page')
        # 获取搜索结果
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })
        # 拼接参数, 返回
        return JsonResponse(data_list, safe=False)

class DetailView(View):
    def get(self,request,sku_id):
    #分类数据， 面包屑，商品信息，规格信息
        try:
            sku=SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
           pass
    #分类数据
        categories=get_categories()
    #面包屑数据
        breadcrumb=get_breadcrumb((sku.category))
    #规格信息
        specs=get_goods_specs(sku)

        context={'categories':categories,
            'breadcrumb':breadcrumb,
            'sku':sku,
            'specs': specs,
        }



        return render(request,'detail.html',context=context)


#统计分类数据访问量
#接收分类id，查询分类信息，获取当天日期，查询访问数据（没有则新增一条，有则累计，
class GoodVisitView(View):
    def post(self,request,cat_id):
        try:
            category=GoodsCategory.objects.get(id=cat_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'无此商品'})

        today=date.today()

        try:
            today_data=GoodsVisitCount.objects.get(category=category,date=today)
        except GoodsVisitCount.DoesNotExist:
            GoodsVisitCount.objects.create(
                category=category,
                date=today,count=1
            )
        else:
            today_data.count +=1
            today_data.save()

        return JsonResponse({'code':0,'errmsg':'done'})











# Create your views here.
# from fdfs_client.client import Fdfs_client
#
# #加载fdfs配置文件创建其客户端
# client=Fdfs_client('common/fastdfs/client.conf')
# #调用客户端传图片法
# client.upload_by_filename('/home/ubuntu/Desktop/11.jpg')

#http://192.168.52.200:8888/group1/M00/00/00/wKg0yF9NB1OAalUSAAGPxxpBsUk614.jpg
#'Group name': 'group1', 'Remote file_id': 'group1/M00/00/00/wKg0yF9NB1OAalUSAAGPxxpBsUk614.jpg', 'Status': 'Upload successed.', 'Local file name': '/home/ubuntu/Desktop/11.jpg', 'Uploaded size': '99.00KB', 'Storage IP': '192.168.52.200'
